package cn.zhouchao.system.aop;

import cn.zhouchao.system.ann.Anndept;
import cn.zhouchao.system.domain.Departmentlog;
import cn.zhouchao.system.mapper.DepartmentlogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.Date;

/**
 * 定义部门的Aop
 */
@Component
@Aspect //定义切面的包
@Slf4j
public class Aopdept {
    //注入service
    @Autowired
    private DepartmentlogMapper departmentlogMapper;

    @Around("@annotation(cn.zhouchao.system.ann.Anndept)")
    public Object AopdeptLog(ProceedingJoinPoint pjp) throws Throwable{
        //1.获取ip
        InetAddress localHost = Inet4Address.getLocalHost();
        String addressIp = localHost.getHostAddress();
        log.info("ip地址为:{}",addressIp);

        //2.创建一个新的时间，作为执行时间
        Date executionTime = new Date();

        //3.获取方法名
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        Anndept annotation = method.getAnnotation(Anndept.class);

        //3.1获取方法描述
        String des = annotation.des();
        log.info("方法描述:{}",des);

        //3.2获取方法名
        String methodname = annotation.methodname();
        log.info("方法名:{}",methodname);

        //创建部门日志对象，并执行添加到数据库
        Departmentlog departmentlog = new Departmentlog();
        //设置ip
        departmentlog.setAddressIp(addressIp);
        //设置执行时间
        departmentlog.setExecutionTime(executionTime);
        //设置方法描述
        departmentlog.setDes(des);
        //设置方法名
        departmentlog.setWeyName(methodname);

        //执行添加方法
        departmentlogMapper.add(departmentlog);

        //执行所有方法
        Object proceed = pjp.proceed();
        //设置返回值
        return proceed;
    }

}
